package edu.zust.zw.shop.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import edu.zust.zw.shop.db.dao.domain.ShopUserDomain;
import edu.zust.zw.shop.util.Result;

public class LoginIntercepter implements HandlerInterceptor {

    private static Logger logger = Logger.getLogger(LoginIntercepter.class);
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // TODO Auto-generated method stub
        logger.info("进入登陆拦截器");
        
        if (null != request.getSession() && null != request.getSession().getAttribute("userInfo")) {
            ShopUserDomain userInfo = (ShopUserDomain) request.getSession().getAttribute("userInfo");
            if (null != userInfo && null != userInfo.getUserId() && !"".equals(userInfo.getUserId())) {
                logger.info("userId = " + userInfo.getUserId());
                return true;
            }
        }
        return makeResponse(response, Result.Code.NO_LOGIN);
    }

    private boolean makeResponse(HttpServletResponse response, Result.Code code) throws Exception {
        response.setHeader("Content-type", "application/json;charset=utf-8");
        response.flushBuffer();
        // response.getOutputStream().write("{\"code\":40304,\"resp\":null,\"msg\":\"账号验证未通过\"}".getBytes("UTF-8"));
        String retString = "{\"code\":" + code.getCode() + ",\"msg\":\"" + code.getMsg() + "\"}";
        response.getOutputStream().write(retString.getBytes("UTF-8"));
        return false;
    }

    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

}
